package cn.ztydata.teachingsystem.heaven.dao;

import cn.ztydata.teachingsystem.heaven.entity.exercise.ExerciseAnalysis;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 习题解析dao
 * Created by wyh on 2015/2/6.
 */
@Repository
public class ExerciseAnalysisDao extends BaseDao{

    /**
     * 批量保存习题解析
     * @param exerciseId 习题ID
     * @param analysises 解析集合
     * @return int[]
     *
     * @author wyh
     * @since 2015-2-7
     */
    public int[] saveAnalysises(long exerciseId, List<ExerciseAnalysis> analysises){
        String sql = "INSERT INTO t_exercise_analysis VALUES(NULL,"+exerciseId+",:analysis)";

        SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(analysises.toArray());

        log.debug("批量保存习题解析");
        return namedParameterJdbcTemplate.batchUpdate(sql,batch);
    }

    /**
     * 习题常规解析
     *
     * @param exerciseId
     * @return
     * @author lyj
     * @since 2015-2-5
     */
    public List<ExerciseAnalysis> getAnalysis(long exerciseId) {
        String sql = "SELECT sAnalysis FROM t_exercise_analysis WHERE iExerciseId=:exerciseId";

        MapSqlParameterSource parameterSource = new MapSqlParameterSource().addValue("exerciseId", exerciseId);

        log.debug("获取习题常规解析");
        return namedParameterJdbcTemplate.query(sql, parameterSource, new RowMapper<ExerciseAnalysis>() {
            @Override
            public ExerciseAnalysis mapRow(ResultSet resultSet, int i) throws SQLException {
                ExerciseAnalysis exerciseAnalysis = new ExerciseAnalysis();

                exerciseAnalysis.setAnalysis(resultSet.getString("sAnalysis"));

                return exerciseAnalysis;
            }
        });
    }

}
